package com.my.util;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

public class Upload {

	/**
	 * 
	 * @param request
	 * @param exts   文件格式限制
	 * @return
	 */
	
	public HashMap<String, Object> uploadFile(HttpServletRequest request,String exts){
		HashMap<String, Object> map = new HashMap<String, Object>();
		String[] fileType = exts.split(",");
		List<String> fileTypes = new ArrayList<String>(Arrays.asList(fileType));
		
		SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
		String filePathDir = "/upload/file"+dateformat.format(new Date());
		String logoRealPathDir = request.getSession().getServletContext().getRealPath(filePathDir);
        File logoSaveFile = new File(logoRealPathDir);
        if (!logoSaveFile.exists()){
        	logoSaveFile.mkdirs();
        }
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
		if (multipartResolver.isMultipart(request)){
			
			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request ;
			Iterator<String> itre = multiRequest.getFileNames();
			List<String> filesname = new ArrayList<String>();
			List<String> cgname = new ArrayList<String>();
			List<String> sbname = new ArrayList<String>();
			while(itre.hasNext()){
				MultipartFile multipartFile=  multiRequest.getFile((String)itre.next());
				String name = multipartFile.getOriginalFilename();
				String ext = name.substring(name.lastIndexOf(".")+1) ;
				if(fileTypes.contains(ext)){
					Random random = new Random(10);
					String fileName = System.currentTimeMillis()+random.nextInt()+"."+ext;
					
					String filePath = logoRealPathDir + "/" + fileName;
					File newFile = new File(logoRealPathDir,fileName);
					try {
						 multipartFile.transferTo(newFile);
						 filesname.add(fileName);
						 cgname.add(name);
						 map.put("type", fileTypes);
						 map.put("file", filesname);
						 map.put(fileName, filePath);
					} catch (Exception e) {
						sbname.add(name);
					}
				}else{
					sbname.add(name);
				}
			}
			if(sbname.size()<=0){
				map.put("success", true);
				map.put("msg", "成功"+cgname.size()+"个,失败"+sbname.size()+"个");
			}else{
				map.put("success", true);
				map.put("msg", "成功"+cgname.size()+"个,失败"+sbname.size()+"个,失败文件为："+sbname+",格式必须为"+fileTypes);
			}
		}
		
		return map;
	}
}
